package com.qinglei.recoup.longconn.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.qinglei.recoup.common.exception.RecoupException;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.longconn.properties.OssProperties;
import com.qinglei.recoup.longconn.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.DisposableBean;

import java.io.File;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Slf4j
public class OssServiceImpl implements OssService, DisposableBean {

    private OSS ossClient;
    private String bucketName;
    private Boolean deleteFile;
    private Executor uploadExecutor;

    public OssServiceImpl(OssProperties ossProperties) throws RecoupException {
        if (ossProperties == null
                || StringUtils.isEmpty(ossProperties.getAccessKeyId())
                || StringUtils.isEmpty(ossProperties.getAccessKeySecret())
                || StringUtils.isEmpty(ossProperties.getBucketName())) {
            throw new RecoupException("oss 缺少配置参数");
        }
        String endpoint = ossProperties.getEndpoint();
        String accessKeyId = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();
        this.bucketName = ossProperties.getBucketName();
        this.ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        if (this.ossClient == null) {
            throw new RecoupException("ossClient 构建失败");
        }
        this.deleteFile = ossProperties.getDeleteFile();
        if (deleteFile == null) {
            deleteFile = true;
        }
        Integer threadNum = ossProperties.getUploadThreadNum();
        if (threadNum == null) {
            threadNum = Runtime.getRuntime().availableProcessors();
            if (threadNum > 4) {
                threadNum = 4;
            }
        }
        this.uploadExecutor = Executors.newFixedThreadPool(threadNum);
        log.info("OssService init complete");
    }

    /**
     * 上传文件
     *
     * @param objectName
     * @param filePath
     */

    //private static Executor uploadExecutorTest = Executors.newFixedThreadPool(2);

    public void uploadFile(String objectName, String filePath) {
        log.info("oss upload objectName: {}, fileName: {}", objectName, filePath);
        CompletableFuture.runAsync(() -> {
            try {
                PutObjectRequest putObjectRequest = new PutObjectRequest(this.bucketName, objectName, new File(filePath));
                PutObjectResult putObjectResult = this.ossClient.putObject(putObjectRequest);
                log.info("oss upload objectName: {}, result: {}", objectName, JsonUtils.objectToJson(putObjectResult));
                if (this.deleteFile) {
//                    boolean delete = new File(filePath).delete();
//                    if (delete) {
//                        log.info("delete file success: {}", filePath);
//                    }
                }
            } catch (Exception e) {
                log.error("oss upload file error", e);
            }
        }, uploadExecutor);
    }

    @Override
    public void destroy() {
        if (this.ossClient != null) {
            this.ossClient.shutdown();
            log.info("ossClient shutdown");
        }
    }

}
